<?php
/**
 *  @department : Commercial development.
 *  @description : This file is part of [example].
 *  example all rights reserved.
 */

namespace app\common\controller;

use app\common\exception\ParamsException;
use app\traits\JsonResponse;
use think\Controller;
use think\Validate;

class BasicController extends Controller
{
    /*
     * JSON交互返回.
     */
    use JsonResponse;

    //前端传参数据
    protected static $data;

    //前端文件数据
    protected static $file;

    //前端文件数据
    protected static $sessionInfo;

    public function __construct()
    {
        parent::__construct();
        $this->getInput();
    }

    /**
     * 在一次请求周期中统一获取输入并过滤函数.
     */
    public function getInput()
    {
        self::$data = filterData($this->request->param(false));

        self::$file = $this->request->file();
    }

    /**
     * 快捷参数验证.
     * @param array $rule    ['account_name|账号' => 'require']
     * @param array $message ['account_name.require' => '账号名必填']
     */
    public function paramsFilter(array $params, array $rule, array $message = [])
    {
        //调用验证器校验
        $validate = new Validate($rule, $message);

        if (!$validate->check($params)) {
            throw new ParamsException($validate->getError(), 2000002);
        }

        return true;
    }

    /**
     * 当前对象回调成员方法.
     *
     * @param string     $method
     * @param array|bool $data1
     * @param array|bool $data2
     *
     * @return bool
     */
    private function _callback($method, &$data1, $data2)
    {
        foreach ([$method, '_' . $this->request->action() . "{$method}"] as $_method) {
            if (method_exists($this, $_method) && false === $this->{$_method}($data1, $data2)) {
                return false;
            }
        }

        return true;
    }

    /**
     * 统一判断管理员后台接口是否带有请求验证信息的会话验证机制.
     */
    public function authSession()
    {
        $session = session(config('session.user'));

        if (empty($session)) {
            if ('DEVELOP' == config('cors.auth_status')) {
                $session = config('cors.develop_session.user');

                self::$sessionInfo = $session;
            }
        }

        self::$sessionInfo = $session;
    }
}
